package middleware

import (
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"login-server/config"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// authMiddleware 验证JWT令牌并在上下文中设置用户ID
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取Authorization头
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "需要Authorization头部"})
			c.Abort()
			return
		}

		// 检查头部是否具有Bearer前缀
		parts := strings.Split(authHeader, " ")
		if len(parts) != 2 || parts[0] != "Bearer" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization头部格式必须为 Bearer {token}"})
			c.Abort()
			return
		}

		// 提取令牌
		tokenString := parts[1]

		// 解析并验证令牌
		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			// 验证签名方法
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("意外的签名方法: %v", token.Header["alg"])
			}
			return []byte(config.GlobalConfig.JWT.Secret), nil
		})

		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "无效或过期的令牌"})
			c.Abort()
			return
		}

		// 验证令牌中的声明
		if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
			// 将用户ID设置在上下文中
			if userID, exists := claims["user_id"]; exists {
				c.Set("userID", uint(userID.(float64)))
				// 可选：也设置用户名以便于访问
				if username, exists := claims["username"]; exists {
					c.Set("username", username.(string))
				}
				c.Next()
				return
			}
		}

		c.JSON(http.StatusUnauthorized, gin.H{"error": "无效的令牌声明"})
		c.Abort()
	}
}
